package com.xizi.zkclient;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.util.List;


public class TestZKClient001 {
    ZooKeeper zkClient;
    @Before
    public void init() throws Exception {
        //创建zkClient
        String serverStrings = "192.168.153.175:2181,192.168.153.176:2181,192.168.153.177:2181";
        zkClient = new ZooKeeper(serverStrings, 2000, new Watcher() {
            @Override
            public void process(WatchedEvent watchedEvent) {
                System.out.println("-------------------------------");
                List<String> children = null;
                try {
                    children = zkClient.getChildren("/", true);

                    for (String child : children) {
                        System.out.println(child);
                    }
                    System.out.println("-------------------------------");
                } catch (KeeperException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    //创建节点
    @Test
    public void CreateNode() throws Exception {
        zkClient.create("/xizizzz","xizizzz".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE,CreateMode.PERSISTENT);
    }

    @Test
    public void getChildren() throws KeeperException, InterruptedException {
        List<String> children = zkClient.getChildren("/", true);
        for (String child : children) {
            System.out.println(child);
        }
        // 延时
        Thread.sleep(Long.MAX_VALUE);
    }

    @Test
    public void exist() throws KeeperException, InterruptedException {

        Stat stat = zkClient.exists("/xizizzz", true);
        System.out.println(stat==null? "不存在 " : "存在");
    }

    //关闭节点 临时节点看不出效果
//    @After
//    public void after() throws Exception {
//        zkClient.close();
//    }
}
